package com.tiyende.kash.loop.utils.track;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;

import com.tiyende.kash.loop.configs.TiyendeApiPath;
import com.tiyende.kash.loop.configs.TiyendeApiUrl;
import com.tiyende.kash.loop.request.HttpHelper;
import com.tiyende.kash.loop.request.IHttpCallback;
import com.tiyende.kash.loop.utils.log.TiyendeLogger;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 埋点收集管理器
 */
public class TrackPointManager {
//    private static final int AUTO_REPORT_THRESHOLD = 20;

    private static volatile TrackPointManager INSTANCE;

    private final TrackPointDao dao;
    private final ExecutorService executor;

    // 私有构造函数防止外部实例化
    private TrackPointManager(Application application) {
        Context appContext = application.getApplicationContext();
        this.dao = TrackDatabase.getDatabase(appContext).trackPointDao();
        this.executor = Executors.newSingleThreadExecutor();
    }

    /**
     * 初始化方法，必须在Application中调用
     * @param application Application上下文
     */
    public static void init(Application application) {
        if (INSTANCE == null) {
            synchronized (TrackPointManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new TrackPointManager(application);
                }
            }
        }
    }

    /**
     * 获取实例，必须先调用init()初始化
     */
    public static TrackPointManager getInstance() {
        if (INSTANCE == null) {
            throw new IllegalStateException("TrackPointManager must be initialized first by calling TrackPointManager.init()");
        }
        return INSTANCE;
    }

    // 记录埋点
    public void track(@NonNull String type, @NonNull String remark) {
        executor.execute(() -> {
            TrackPoint point = new TrackPoint(type, remark, System.currentTimeMillis());
            dao.insert(point);
            // 检查是否达到自动上报阈值
//            if (dao.getUnreportedCount() >= AUTO_REPORT_THRESHOLD) {
//                reportData();
//            }
        });
    }

    // 手动触发上报
    public void manualReport() {
        executor.execute(this::reportData);
    }

    // 上报数据
    private void reportData() {
        List<TrackPoint> unreportedPoints = dao.getUnreportedPoints();
        if (unreportedPoints.isEmpty()) return;

        try {
            // 这里替换为你的实际上报逻辑
            reportToServer(unreportedPoints, new IHttpCallback() {
                @Override
                public void onRequestSuccess(@NonNull JSONObject data) {
                    int code = data.optInt("code");
                    if (code == 0){
                        //更新事件状态为已上报
                        updateTrackPointsStatus(unreportedPoints);
                    }
                }
                @Override
                public void onRequestError(@NonNull JSONObject error) {
                }
                @Override
                public void onRequestFinish() {
                }
            });
        } catch (Exception e) {
            // 上报失败处理
            TiyendeLogger.e("track report error!");
        }
    }

    // 实际上报方法(需要根据你的API实现)
    private void reportToServer(List<TrackPoint> points, IHttpCallback callback) {
        //上报
        JSONObject params = new JSONObject();
        try {
            params.put("path", TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_TRACK_EVENT_BATCH_PATH);
            JSONArray array = new JSONArray();
            for (TrackPoint point : points){
                TiyendeLogger.e("track event >>> id=" + point.id + ">>>type=" + point.type + ">>>remark=" + point.remark + ">>>timestamp=" + point.timestamp + ">>>isReported=" + point.status);
                JSONObject obj = new JSONObject();
                obj.put("id", point.id);
                obj.put("type", point.type);
                obj.put("remark", point.remark);
                obj.put("timestamp", point.timestamp);
                array.put(obj);
            }
            params.put("list",array);
        } catch (JSONException e) {
            TiyendeLogger.e("track params format failed!");
        }
        String httpUrl = TiyendeApiUrl.INSTANCE.getTiyendeHttpUrl(false,-1);
        HttpHelper.INSTANCE.postPoint(httpUrl,params,callback);
    }

    /**
     * 更新事件状态
     * @param points：所有事件列表
     */
    private void updateTrackPointsStatus(List<TrackPoint> points) {
        executor.execute(() -> {
            // 标记为已上报
            for (TrackPoint point : points) {
                point.status = 1;
                dao.update(point);
            }
            // 清理已上报的数据
            dao.deleteReportedPoints();
        });
    }

    // 清理资源
    public void release() {
        executor.shutdown();
        INSTANCE = null;
    }
}
